import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Arrays;
public class NGuessNumber  extends JFrame implements ActionListener{
    JTextField jtf=new JTextField(16);
    JButton b1=new JButton("确定"),
            b2=new JButton("重玩一局"),
            b3=new JButton("看答案");
    JLabel jl1=new JLabel("请输入四个不同数字："),
            jl2=new JLabel(" ");
    int[] right=new int[4];
    int count=0,A,B;
    public NGuessNumber(){
        super("猜数字");
        fill(right,9);
        setLayout(new FlowLayout(FlowLayout.CENTER));
        add(jl1);add(jtf);add(jl2);add(b1);add(b3);add(b2);
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(330,250);
        setVisible(true);
    }
    public void fill(int[] a,int b)
    {
        //给数组填充不同的1到b的数字
        for(int i=0;i<a.length;i++){

            a[i]=(int)(Math.random()*b+1);
            while(true){

                if(in_it(a[i],a,i))a[i]=(int)(Math.random()*b+1);

                else
                    break;
            }
        }
    }
    public boolean in_it(int num,int[] before,int n){//判断num是否在数组before的前n项内
        for(int i=0;i<n;i++)
            if(num==before[i])return true;
        return false;

    }
    public void actionPerformed(ActionEvent e){

        if(e.getSource()==b1){

            count++;
            String s=jtf.getText();
            if(s.length()!=4)jl2.setText("格式错误");
            else {

                A=0;B=0;

                for(int i=0;i<4;i++)

                    for(int j=0;j<4;j++)
                        if((s.charAt(i)-'0')==right[j])
                        {
                            if(i==j)A++;
                            else B++;
                        }
                if(A==4){jl2.setText("RIGHT！猜了"+count+"次");
                    count=0;
                }
                else jl2.setText("提示："+A+"A"+B+"B");
            }
        }
        if(e.getSource()==b2){
            fill(right,9);
            jtf.setText("");
            jl2.setText(" ");
        }
        if(e.getSource()==b3){
            jl2.setText(Arrays.toString(right));
        }
    }
    public static void main (String[] args) {
        new NGuessNumber();
    }


}